package cn.enilu.guns.admin.modular.door;

import cn.enilu.guns.admin.core.base.controller.BaseController;
import cn.enilu.guns.admin.core.base.tips.SetDataToDeviceTip;
import cn.enilu.guns.admin.equipment.dto.DeviceInfo;
import cn.enilu.guns.admin.equipment.service.EntranceGuardService;
import cn.enilu.guns.admin.equipment.transform.GetDeviceDataTransform;
import cn.enilu.guns.admin.modular.thread.ReadTimeThread;
import cn.enilu.guns.bean.constant.factory.PageFactory;
import cn.enilu.guns.bean.core.ShiroUser;
import cn.enilu.guns.bean.dto.RealTimeRecordDto;
import cn.enilu.guns.bean.entity.door.EntranceGuardRule;
import cn.enilu.guns.bean.entity.door.EquipmentInfo;
import cn.enilu.guns.bean.entity.door.EventType;
import cn.enilu.guns.bean.vo.query.Page;
import cn.enilu.guns.bean.vo.query.SearchFilter;
import cn.enilu.guns.dao.cache.impl.EhcacheDao;
import cn.enilu.guns.service.door.EquipmentInfoService;
import cn.enilu.guns.service.door.EventTypeService;
import cn.enilu.guns.service.system.impl.ConstantFactory;
import cn.enilu.guns.shiro.ShiroKit;
import cn.enilu.guns.utils.*;
import cn.enilu.guns.warpper.door.DeviceInfoWarpper;
import cn.enilu.guns.warpper.door.EquipmentInfoWarpper;
import cn.enilu.guns.warpper.door.RealTimeRecordDtoWarpper;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;

@Controller
@RequestMapping("/door/real/time")
public class RealTimeController extends BaseController {
	private  Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private EhcacheDao ehcacheDao;
	@Autowired
	private EntranceGuardService entranceGuardService;
	@Autowired
	private EquipmentInfoService equipmentInfoService;
    @Autowired
    private EventTypeService eventTypeService;

	public static final String REAL_TIME = "realTime";

	private static String PREFIX = "/door/real/time/";

	/**
	* 跳转到首页
	*/
	@RequestMapping(value="",method = RequestMethod.GET)
		public String index() {
			//设置开启监控的设备列表
			ReadTimeThread.clearEquipmentInfoMap(getRealTimeUserKey());
			return PREFIX + "index.html";
		}

	/**
	 * 获取所有的设备数据
	 * @param equipmentName
	 * @return
	 */
	@RequestMapping(value = "/listEquipment",method = RequestMethod.POST)
	@ResponseBody
	public Object listEquipment(@RequestParam(required = false) String equipmentName) {
		Map<Long,EquipmentInfo> openEquipmentInfoMap = ReadTimeThread.getUserEquipmentInfoMap(getRealTimeUserKey());
		List<SearchFilter> searchFilters = Lists.newArrayList();
		if(!StringUtils.isNullOrEmpty(equipmentName)) {
			searchFilters.add(SearchFilter.build("equipmentName", SearchFilter.Operator.EQ, equipmentName));
		}
		List<EquipmentInfo> equipmentInfos = equipmentInfoService.queryAll(searchFilters, new Sort(Sort.Direction.ASC, "id"));
		if(null != openEquipmentInfoMap) {
			for (EquipmentInfo equipmentInfo : equipmentInfos) {
				if (openEquipmentInfoMap.containsKey(equipmentInfo.getId())) {
					equipmentInfo.setOpenStatus("1");
				} else {
					equipmentInfo.setOpenStatus("0");
				}
//			if(entranceGuardService.checkDeviceOnline(equipmentInfo.getIpAddress())){
//				equipmentInfo.setOnlineStatus("1");
//			}else{
//				equipmentInfo.setOnlineStatus("0");
//			}
			}
		}
		return super.warpObject(new EquipmentInfoWarpper(BeanUtil.objectsToMaps(equipmentInfos)));
	}
	/**
	* 关闭监控
	*/
	@RequestMapping(value = "/closeRealTime")
	@ResponseBody
	public Object closeRealTime(EquipmentInfo equipmentInfo) {
		if(equipmentInfo.getId() == null){
			return new SetDataToDeviceTip(300,"关闭监控失败，请选择一台设备");
		}
		equipmentInfo = equipmentInfoService.get(equipmentInfo.getId());
		ReadTimeThread.removeEquipmentInfo(getRealTimeUserKey(),equipmentInfo);
        return new SetDataToDeviceTip(200,"关闭监控成功");
	}
	/**
	 * 开启监控
	 */
	@RequestMapping(value = "/openRealTime")
	@ResponseBody
	public Object openRealTime(EquipmentInfo equipmentInfo) {
		if(equipmentInfo.getId() == null){
			return new SetDataToDeviceTip(300,"关闭监控失败，请选择一台设备");
		}
		equipmentInfo = equipmentInfoService.get(equipmentInfo.getId());

		SetDataToDeviceTip setDataToDeviceTip;
		if(ReadTimeThread.putEquipmentInfo(getRealTimeUserKey(),equipmentInfo)){
			setDataToDeviceTip = new SetDataToDeviceTip(200,"开启监控成功");
		}else{
			setDataToDeviceTip = new SetDataToDeviceTip(200,"开启监控失败,设备不在线");
		}
//		Map<Long,EquipmentInfo> openEquipmentInfoMap = ReadTimeThread.getUserEquipmentInfoMap(getRealTimeUserKey());
		return setDataToDeviceTip;
	}


	/**
	 * Session中获取开启监控的设备列表
	 * @return
	 */
//	private Map<Long,EquipmentInfo> getOpenRealTimeMap(){
//		HttpSession session = this.getSession();
//		ShiroUser shiroUser = ShiroKit.getUser();
//		return (Map<Long,EquipmentInfo>)session.getAttribute(REAL_TIME + shiroUser.getId());
//	}

	/**
	 * 设置开启监控的设备列表，放入Session中
//	 * @param equipmentInfos
	 * @return
	 */
//	private void setOpenRealTimeMap(Map<Long,EquipmentInfo> equipmentInfos){
//		HttpSession session = this.getSession();
//		ShiroUser shiroUser = ShiroKit.getUser();
//		session.setAttribute(REAL_TIME + shiroUser.getId(),equipmentInfos);
//	}

	private String getRealTimeUserKey(){
        ShiroUser shiroUser = ShiroKit.getUser();
        return REAL_TIME + shiroUser.getId() + HttpKit.getIp();
    }

    //获取实时数据，返回list
    @RequestMapping(value = "/realTimeStart",method = RequestMethod.POST)
    @ResponseBody
    public Object realTimeStart() {
        ReadTimeThread.startRead();
		return new SetDataToDeviceTip(200,"开始获取数据");
    }
	//获取实时数据，返回list
	@RequestMapping(value = "/realTimeStop",method = RequestMethod.POST)
	@ResponseBody
	public Object realTimeStop() {
		ReadTimeThread.clearEquipmentInfoMap(getRealTimeUserKey());
		return new SetDataToDeviceTip(200,"停止获取数据");
	}
	//获取实时数据，返回list
	@RequestMapping(value = "/listRealTimeRecord",method = RequestMethod.POST)
	@ResponseBody
	public Object listRealTimeRecord() {
		ReadTimeThread.resetStartTime();
		List<RealTimeRecordDto> realTimeRecordDtos = Lists.newArrayList();
		Queue<RealTimeRecordDto> realTimeRecordDtoQueue = ReadTimeThread.getRealTimeRecordDto(getRealTimeUserKey());
		if (null != realTimeRecordDtoQueue) {
			int length = realTimeRecordDtoQueue.size();
				while (length != 0) {
					RealTimeRecordDto realTimeRecordDto = realTimeRecordDtoQueue.poll();
					EventType eventType = ehcacheDao.hget(EhcacheDao.EVENT_TYPE,realTimeRecordDto.getEventType(),EventType.class);
					if (eventType != null) {
						realTimeRecordDto.setEventName(eventType.getEventName());
						realTimeRecordDto.setEventStatus(eventType.getEventStatus());
					}
					realTimeRecordDtos.add(0,realTimeRecordDto);
				length--;
			}
		}
        return super.warpObject(new RealTimeRecordDtoWarpper(BeanUtil.objectsToMaps(realTimeRecordDtos)));
	}
}